// pages/joinGroup/joinGroup.js
const app = getApp()
var wh = require("../../utils/wh.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shop: [],
    sponsor:'',//团长
    joiner: '',//参与者
    group_id:'',
    sponsor_id:'',
    cutdown: {
      'dd': 0, 
      'hh': 0, 
      'mm': 0,
      'ss': 0
    }, //倒计时
    other_cutdown: {
      'hh': 0,
      'mm': 0,
      'ss': 0
    }, //倒计时
    setintvalid: null,
    setintvalids: null,
    notcut: false, //活动是否结束
    notcuts: false, //参团是否结束
    groupInfo: '',
    goodsInfo: '',
    userData: '',
    is_me:'',
  },

  // 获取拼团详情
  getgroupDetail(group_id) {
    let that = this;
    wh.Post('/api/mall.group/detail', {
      group_id: group_id
    }, function (res) {
      clearInterval(that.setintvalid); //清除倒计时
      let thistime = new Date().getTime(); //判断时间
      let start_time = res.start_time + '000'; //精确到毫秒数 
      let end_time = res.group.end_time + '000'; //精确到毫秒数 
      if (thistime <= start_time) { //当前时间小于开始时间 活动未开始
        that.start_bargain(start_time, thistime, end_time);
      } else if (thistime < end_time) { //当前时间小于结束时间 活动进行中
        that.end_bargain(end_time, thistime);
      } else {
        that.setData({
          notcut: true
        }); //活动结束
      }
      console.log('拼团详情', res)
      that.setData({
        groupInfo: res.group,
        goodsInfo: res.goods,
      })
    })
  },
  //活动未开始
  start_bargain: function (start_time, thistime, end_time) {

    let that = this;
    let cha = start_time - thistime; //开始时间减去现在时间

    that.setintvalid = setInterval(function () {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.end_bargain(end_time, thistime);
      }
      that.time_meter(cha);
    }, 1000);
  },

  //活动已开始
  end_bargain: function (end_time, thistime) {
    let cha = end_time - thistime;
    let that = this;

    that.setintvalid = setInterval(function () {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalid);
        cha = 0;
        that.setData({
          notcut: true
        });
        return;
      }
      that.time_meter(cha)
    }, 1000);
  },
  //参团活动倒计时
  my_time_bargain: function (end_time, thistime) {
    let cha = end_time - thistime;
    let that = this;
    that.setintvalids = setInterval(function () {
      cha -= 1000;
      if (cha <= 0) {
        clearInterval(that.setintvalids);
        cha = 0;
        that.setData({
          notcuts: true
        });
        return;
      }
      that.my_time_meter(cha)
    }, 1000);
  },
  //时间计算
  time_meter: function (timer) {
    let that = this;
    let dd = parseInt(timer / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
    let hh = parseInt(timer / 1000 / 60 / 60 % 24, 10); //计算剩余的小时数
    let mm = parseInt(timer / 1000 / 60 % 60, 10); //计算剩余的分钟数
    let ss = parseInt(timer / 1000 % 60, 10); //计算剩余的秒数
    mm = that.checkTime(mm);
    ss = that.checkTime(ss);
    let cutdown = {
      'dd': dd,
      'hh': hh,
      'mm': mm,
      'ss': ss
    };
    that.setData({
      cutdown: cutdown
    })
  },
  //时间计算2
  my_time_meter: function (timer) {
    let that = this;
    let dd = parseInt(timer / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
    let hh = parseInt(timer / 1000 / 60 / 60 % 24, 10); //计算剩余的小时数
    let mm = parseInt(timer / 1000 / 60 % 60, 10); //计算剩余的分钟数
    let ss = parseInt(timer / 1000 % 60, 10); //计算剩余的秒数
    mm = that.checkTime(mm);
    ss = that.checkTime(ss);
    let other_cutdown = {
      'hh': hh,
      'mm': mm,
      'ss': ss
    };
    that.setData({
      other_cutdown: other_cutdown
    })
  },
  checkTime: function (i) {
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },
  //时间戳
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp * 1000),//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      Y = date.getFullYear() + '-',
      M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-',
      D = date.getDate() + ' ',
      h = date.getHours() + ' : ',
      m = date.getMinutes() + ' : ',
      s = date.getSeconds();
    return h + m + s;
  },
  // 获取别人的拼团
  other(group_id) {
    let that = this;
    wh.Post('/api/mall.group/others?', {
      group_id: group_id,
      page: 1,
      page_num: 3
    }, function (res) {
      for (var i = 0; i < res.length; i++) {
        res[i].count_down = that.timestampToTime(res[i].count_down)
      }
      that.setData({
        otherlist: res,
      })
      console.log('别人的拼团', res)
    })
  },
  // 获取拼团列表
  lists() {
    let that = this;
    let page_size = this.data.page_size,
      no_data = this.data.no_data,
      page = this.data.page;
      wh.Post('/api/mall.group/lists', {
        is_recom:1
      }, function (res) {
        that.setData({
          shop: res
        })
      })
  },
  // 获取团长信息（发起者）
  sponsor(sponsor_id){
    let that=this;
    wh.Post('/api/mall.group/sponsor', { sponsor_id: sponsor_id }, function (res) {
      console.log('团长',res)
      clearInterval(that.setintvalids); //清除倒计时
      let thistime = new Date().getTime(); //判断时间
      console.log(thistime)
      let start_time = res.start_time + '000'; //精确到毫秒数 
      let end_time = res.count_down + '000'; //精确到毫秒数 
      console.log(end_time)
      
      if (thistime < end_time) { //当前时间小于结束时间 活动进行中
        that.my_time_bargain(end_time, thistime);
      } else {
        that.setData({
          notcuts: true
        }); //活动结束
      }
      that.setData({
        sponsor:res,
      })
    })
  },
  // 获取团长发起拼团参与者列表
  joiner(sponsor_id, group_number) {
    let that = this;
    wh.Post('/api/mall.group/joiner', { 
      sponsor_id: sponsor_id,
      page:1,
      page_num:10
     }, function (res) {
       let inv = res.list,
         tmp_arr = [];
       for (let i = 0; i < group_number; i++) {
         if (inv[i]) {
           tmp_arr.push(inv[i]);
         } else {
           tmp_arr.push({});
         }
       }
       console.log('拼团参与者列表',res)
       that.setData({
         joiner: tmp_arr,
         is_me: res.is_me
       })
    })
  },
//用户参团
  join(){
    let that = this;
    wh.Post('/api/mall.group/join', { sponsor_id: that.data.sponsor_id},function(res){
      console.log('用户参团',res)
      // if (res.pay==1){
      //   wx.showToast({
      //     title: '您已经参与过该拼团了',
      //     icon: 'none',
      //     duration: 2000,
      //   })
      // }else{
        let istype = 1;//用来判断是拼团进入支付页面的
        wx.navigateTo({
          url: '../submit/submit?istype=' + istype + '&user_gro_id=' + res.join_id,
        })
      // }
    })
  },
  // 立即参团
  joinGroup(e) {
    let that = this;
    wx.redirectTo({
      url: '../joinGroup/joinGroup?sponsor_id=' + e.currentTarget.dataset.id + '&group_id=' + that.data.group_id + '&group_number=' + that.data.groupInfo.group_number,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var userData = wx.getStorageSync('W_Userinfo')
    this.setData({
      userData: JSON.parse(userData)
    });
    this.lists()
    console.log(options.sponsor_id)
    this.sponsor(options.sponsor_id)
    this.joiner(options.sponsor_id, options.group_number)
    console.log(options.group_id)
    this.getgroupDetail(options.group_id)
    this.other(options.group_id)
    this.setData({
      group_id: options.group_id,
      sponsor_id: options.sponsor_id,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.app_auth(this)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let title = this.data.userData.nickname + '正在参加' + this.data.groupInfo.group_title,
    imgUrl = this.data.groupInfo.group_cover,
      group_id=this.data.group_id,
      group_number = this.data.groupInfo.group_number,
      sponsor_id = this.data.sponsor_id; 
    return {
      title: title,
      imageUrl: imgUrl,
      path: '/pages/joinGroup/joinGroup?sponsor_id=' + sponsor_id + '&group_id=' + group_id + '&group_number=' + group_number,
      success: function (res) {
        // 转发成功
        wx.showToast({
          title: '已成功邀请',
          icon: 'success',
          duration: 2000
        })
      },
    }
  }
})